import React, {Component} from 'react';
import {
    View, Image, TouchableOpacity, Modal, Text, ListView, Platform,Dimensions,StyleSheet,Alert,
    DeviceEventEmitter,
    NativeAppEventEmitter,
    InteractionManager
} from 'react-native';

import _ from 'lodash';
// import data from './city-list-new.json';
import Toast, {DURATION} from 'react-native-easy-toast';
import LoadingTip from '../LoadingTip';

const {width,height} = Dimensions.get('window')
const SECTIONHEIGHT = 30,ROWHEIGHT = 44
//这是利用lodash的range和数组的map画出26个英文字母
const letters = _
    .range('A'.charCodeAt(0), 'Z'.charCodeAt(0) + 1)
    .map(n => String.fromCharCode(n).substr(0))
    _.pull(letters,'O','V')//去掉o和V,这两个下面没有城市
let city=[]//城市的数组
let data = null;
var totalheight=[];//每个字母对应的城市和字母的总高度
var that = null;
export default class List extends Component {
    constructor(props) {
        super(props);
        var getSectionData = (dataBlob, sectionID) => {
        return dataBlob[sectionID];
        };
        var getRowData = (dataBlob, sectionID, rowID) => {
        return dataBlob[rowID];
        };

        city = [];
        totalheight = [];

        this.state={
             dataSource:new ListView.DataSource({
                getRowData: getRowData,
                getSectionHeaderData: getSectionData,
                rowHasChanged: (row1, row2) => row1 !== row2,
                sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
            }),
            showLoading: true,
            curCity: props.curCity,
            location_city: props.location_city,
        }
    that = this
    }
    componentWillMount(){
        city = [];
        totalheight = [];

    }
    componentDidMount() {
        this.setState({
            showLoading: true
        },()=>{
            InteractionManager.runAfterInteractions(() => {
                setTimeout(async()=>{
                    DATA_JSON = await require('./city-list-new.json');
                    if(DATA_JSON.CITIES){
                        data = DATA_JSON;
                        //把城市放到对应的字母中
                        for(let j = 0;j<letters.length;j++){
                            let each =[]
                            for(let i = 0;i<data.CITIES.length;i++){
                                if(letters[j] == data.CITIES[i].name_en.substr(0,1) ){
                                    each.push(data.CITIES[i].name);
                                }
                            }
                            let _city={}
                            _city.index = letters[j]
                            _city.name = each
                            city.push(_city)
                        }

                        // 更新view
                        this.updateView();

                    }
                },100);

            });
        });

    }

    updateView() {
        var dataBlob = {};
        var sectionIDs = [];
        var rowIDs = [];

        for(let ii = 0;ii<city.length;ii++){
            var sectionName = 'Section ' + ii;
            sectionIDs.push(sectionName)
            dataBlob[sectionName] = letters[ii]
            rowIDs[ii] = [];

            for(let j = 0;j<city[ii].name.length;j++){
                var rowName = ii + '-' + j;
                rowIDs[ii].push(rowName)
                dataBlob[rowName] = city[ii].name[j]
            }
            //计算每个字母和下面城市的总高度，递增放到数组中
            // var eachheight = this.props.sectionHeight+this.props.rowHeight*newcity.length
            var eachheight = SECTIONHEIGHT+ROWHEIGHT*city[ii].name.length;
            totalheight.push(eachheight);
        }
        this.setState({
            dataSource: this.state.dataSource.cloneWithRowsAndSections(dataBlob, sectionIDs, rowIDs),
            showLoading: false
        });
    }

    renderRow(rowData,rowId){
        return (
            <TouchableOpacity
            key={rowId}
            style={[styles.rowdata,{height:ROWHEIGHT,justifyContent:'center',marginLeft:15}]}
             onPress={()=>{that.changedata(rowData)}}>
             <Text style={styles.rowdatatext}>{rowData}</Text>
            </TouchableOpacity>
        )
    }
    renderSectionHeader = (sectionData, sectionID) => {
        return (
        <View style={{height:SECTIONHEIGHT,justifyContent:'center',paddingLeft:15, backgroundColor:'#F3F3F3'}}>
            <Text  style={{color:'#565656',fontWeight:'bold',fontSize: 17,}}>
                {sectionData}
            </Text>
        </View>
        )
    }
    // render ringht index Letters
    renderLetters(letter, index) {
        return (
            <TouchableOpacity key={index} activeOpacity={0.6} onPress={()=>{this.scrollTo(index,letter)}}>
                <View style={styles.letter}>
                    <Text style={styles.letterText}>{letter}</Text>
                </View>
            </TouchableOpacity>
        )
    }
        //回调改变显示的城市
    changedata=(cityname)=>{
        if(this.props.changeCity){
            this.props.changeCity(cityname)
            return;
        }
        this.props.navigator && this.props.navigator.pop();
        
        let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
        Emitter.emit('update.city', cityname);


    }

    //touch right indexLetters, scroll the left
    scrollTo=(index, letter)=>{
        this.refs.toast.close();

        let position=0;
        for(let i = 0;i<index;i++){
            position += totalheight[i]
        }
        this._listView.scrollTo({
            y:position
        });

        this.refs.toast.show(letter, DURATION.LENGTH_SHORT);
    }

    render() {
        return (
            <View style={{height: Dimensions.get('window').height,marginBottom:10,flex:1}}>
                {this.state.location_city && this.state.location_city == this.state.curCity?<View style={{height: 44, borderBottomWidth: 0.5,justifyContent:'center', borderBottomColor: '#DDDDDD',paddingLeft: 15, backgroundColor:'#fff'}}>
                    <Text style={{color:'#7B7B7B',fontSize: 15}}>定位城市：<Text style={{color: '#EA5404'}}>{this.state.location_city}</Text></Text>
                </View>:(this.state.curCity?<View style={{height: 44, borderBottomWidth: 0.5,justifyContent:'center', borderBottomColor: '#DDDDDD',paddingLeft: 15, backgroundColor:'#fff'}}>
                    <Text style={{color:'#7B7B7B',fontSize: 15}}>当前城市：<Text style={{color: '#EA5404'}}>{this.state.curCity}</Text></Text>
                </View>:(this.props.code==13?<View style={{height: 44, borderBottomWidth: 0.5,justifyContent:'center', borderBottomColor: '#DDDDDD',paddingLeft: 15, backgroundColor:'#fff'}}>
                    <Text style={{color:'#7B7B7B',fontSize: 15}}>您未开启定位功能</Text>
                </View>:null))}
                <View style={{flex:1}}>
                    <ListView
                        contentContainerStyle={styles.contentContainer}
                        ref={listView => this._listView = listView}
                        dataSource={this.state.dataSource}
                        renderRow={this.renderRow}
                        renderSectionHeader={this.renderSectionHeader}
                        enableEmptySections={true}
                        initialListSize={500}
                    />
                </View>

                <View style={styles.letters}>
                    {letters.map((letter, index) => this.renderLetters(letter, index))}
                </View>
                {this.state.showLoading?<LoadingTip show={this.state.showLoading}/>:null}
                <Toast ref="toast" position='top' positionValue={200} fadeInDuration={750} fadeOutDuration={1000} opacity={0.8}/>
            </View>
        );
    }
};

const styles = StyleSheet.create({
    contentContainer: {
        width: width,
        backgroundColor: 'white',
    },
    letters: {
        position: 'absolute',
        height: height - 60 - 64,
        top: 0,
        bottom: 0,
        right: 0,
        backgroundColor: '#F0F0F0',
        borderRadius: 20,
        justifyContent: 'center',
        alignItems: 'center',
    },
    letter: {
        height: height*3.3/100,
        width: width*3/50,
        justifyContent: 'center',
        alignItems: 'center',
    },
    letterText: {
        textAlign: 'center',
        fontSize: height*1.1/50,
        color:'#999999'
    },
    rowdata:{
        borderBottomColor:'#DDDDDD',
        borderBottomWidth:0.5,
        justifyContent: 'center'
    },
    rowdatatext:{
        color:'#7B7B7B',
        justifyContent: 'center'
    }
});
